package com.example.changtest.ui.view


import android.content.Context
import android.graphics.Camera
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import androidx.annotation.Nullable
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.changtest.util.LogUtil


/**
 * @Description:
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/2/28 11:12
 */
class BliConstraintLayout constructor(context: Context) : ConstraintLayout(context) {

    private var rotateY = 0f

    private var isLeftRotate = true

   // private val matrix: Matrix = Matrix()
    private var matrixCustom: Matrix = Matrix()

    private val camera: Camera = Camera()

//    open fun BliConstraintLayout(context: Context) {
//        super(context)
//    }

    //kotlin为我们提供了一个init代码块,
    //init代码块的执行顺序在主构造方法之后
    //我们可以在init代码块中进行各种初始化操作
    //init代码块中可以访问主构造方法中的变量
    init {

    }

    //当主构造器和次构造器同时存在时，次构造器必须直接或者间接调用主构造器
    constructor(context: Context, @Nullable attrs: AttributeSet?) : this(context){
        //super(context, attrs)
    }
    //执行顺序上，主构造器>init代码块>次构造器

    constructor(context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int
    ) :this(context, attrs) {

    }


    override fun dispatchDraw(canvas: Canvas) {
        //camera保存状态
        camera.save()
        //camera设置绕Y轴旋转角度
        camera.rotateY(rotateY)
        //将变换应用到canvas上
        camera.applyToCanvas(canvas)
        camera.getMatrix(matrixCustom)
        LogUtil.e("width:${width},height:${height}")
        if (!isLeftRotate) {
            //设置靠左进行旋转
            matrixCustom.preTranslate(-width.toFloat(), (-height shr 1).toFloat()) // - getHeight() >> 1  相当于 - getHeight() / 2
            matrixCustom.postTranslate(width.toFloat(), (height shr 1).toFloat())
        } else {
            //设置靠右进行旋转
            matrixCustom.preTranslate(0f,  (-height shr 1).toFloat())
            matrixCustom.postTranslate(0f, (height shr 1).toFloat())
        }
        canvas.setMatrix(matrixCustom)
        //camera恢复状态
        camera.restore()
        super.dispatchDraw(canvas)
    }

    fun setRotateY(rotateY: Float) {
        this.rotateY = rotateY
        invalidate()
    }

    fun setIsLeftRotate(isLeft: Boolean) {
        isLeftRotate = isLeft
    }
}